package com.changpei.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.URL;
import java.util.UUID;

/**
 * @author weibiao
 */
@Slf4j
@SuppressWarnings("all")
public class FileUtil {

    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
        createTarget(filePath);
        FileOutputStream out = new FileOutputStream(filePath + fileName);
        out.write(file);
        out.flush();
        out.close();
    }

    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            return file.delete();
        } else {
            return false;
        }
    }

    /**
     * 下载文件
     * @param imgUrl
     * @param filePath
     * @return
     */
    public static String downloadPicture(String imgUrl, String filePath) {
        try {
            URL url = new URL(imgUrl);
            String fileName = FileUtil.renameToUuid(imgUrl);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());

            FileOutputStream fileOutputStream = new FileOutputStream(filePath + fileName);
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int length;
            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            fileOutputStream.write(output.toByteArray());
            dataInputStream.close();
            fileOutputStream.close();
            return fileName;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void writeFile(String content, String filePath, String fileName) throws Exception {
        createTarget(filePath);
        PrintWriter pw = new PrintWriter(filePath + fileName);
        pw.print(content);
        pw.close();
    }

    public static void createTarget(String filePath) {
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
    }

    public static String renameToUuid(String fileName) {
        return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
    }

}
